package com.southminority.ethnic.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

/**
 * 安全配置类
 * 
 * @author SouthMinority
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    /**
     * 密码编码器
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 安全过滤器链配置
     */
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            // 禁用CSRF保护（对于API接口）
            .csrf(csrf -> csrf.disable())
            // 启用CORS支持
            .cors(cors -> cors.configurationSource(request -> {
                var corsConfiguration = new org.springframework.web.cors.CorsConfiguration();
                corsConfiguration.setAllowedOriginPatterns(java.util.List.of("*"));
                corsConfiguration.setAllowedMethods(java.util.List.of("GET", "POST", "PUT", "DELETE", "OPTIONS"));
                corsConfiguration.setAllowedHeaders(java.util.List.of("*"));
                corsConfiguration.setAllowCredentials(true);
                corsConfiguration.setMaxAge(3600L);
                return corsConfiguration;
            }))
            // 配置会话管理为无状态
            .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            // 配置授权规则 - 与TokenAuthenticationInterceptor保持一致
            .authorizeHttpRequests(auth -> auth
                // === 前端展示接口 - 全部放行 ===
                .requestMatchers("/api/**").permitAll()           // 前端API展示
                .requestMatchers("/user/**").permitAll()          // 用户相关接口
                .requestMatchers("/course/**").permitAll()        // 课程接口
                .requestMatchers("/language-**").permitAll()      // 语言文化接口
                .requestMatchers("/contact/**").permitAll()       // 联系方式接口
                
                // === 管理端接口 - 由TokenAuthenticationInterceptor处理认证 ===
                .requestMatchers("/admin/**").permitAll()         // 管理接口(由拦截器验证)
                .requestMatchers("/vipadmin/**").permitAll()      // VIP管理接口(由拦截器验证)
                .requestMatchers("/aliyunOss/**").permitAll()     // OSS接口(由拦截器验证)
                
                // === 系统接口 - 放行 ===
                .requestMatchers("/swagger-ui/**", "/v3/api-docs/**").permitAll()  // API文档
                .requestMatchers("/error").permitAll()            // 错误页面
                
                // === OPTIONS预检请求 - 放行 ===
                .requestMatchers(org.springframework.http.HttpMethod.OPTIONS, "/**").permitAll()
                
                // === 默认放行所有其他接口 ===
                .anyRequest().permitAll()
            );

        return http.build();
    }
}
